/**
 * 系统管理器
 */
class SystemManager {
    constructor() {
        this.init();
    }

    init() {
        console.log('Initializing SystemManager...');
        
        // 确保DOM已加载
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.initializeElements());
        } else {
            this.initializeElements();
        }
    }

    initializeElements() {
        console.log('Initializing SystemManager elements...');
        
        // 获取DOM元素
        this.saveConfigBtn = document.getElementById('saveConfigBtn');
        this.refreshSystemInfoBtn = document.getElementById('refreshSystemInfoBtn');
        this.clearAllIndexBtn = document.getElementById('clearAllIndexBtn');
        this.clearDirectoryIndexBtn = document.getElementById('clearDirectoryIndexBtn');
        this.setIndexDirectoryBtn = document.getElementById('setIndexDirectoryBtn');
        this.settingsOperationResult = document.getElementById('settingsOperationResult');
        this.settingsOperationContent = document.getElementById('settingsOperationContent');

        // 绑定事件
        if (this.saveConfigBtn) {
            console.log('Binding saveConfigBtn click event');
            this.saveConfigBtn.addEventListener('click', () => this.saveConfig());
        } else {
            console.error('saveConfigBtn element not found');
        }

        if (this.refreshSystemInfoBtn) {
            this.refreshSystemInfoBtn.addEventListener('click', () => this.refreshSystemInfo());
        }

        if (this.clearAllIndexBtn) {
            this.clearAllIndexBtn.addEventListener('click', () => this.clearAllIndex());
        }

        if (this.clearDirectoryIndexBtn) {
            this.clearDirectoryIndexBtn.addEventListener('click', () => this.clearDirectoryIndex());
        }
        
        if (this.setIndexDirectoryBtn) {
            this.setIndexDirectoryBtn.addEventListener('click', () => this.setIndexDirectory());
        }

        // 页面加载时恢复索引目录和加载系统信息
        this.loadSavedIndexDirectory();
        this.loadConfig();
        this.refreshSystemInfo();
    }

    async setIndexDirectory() {
        const indexDirectories = this.getIndexDirectories();
        
        if (indexDirectories.length === 0) {
            this.showAlert('请至少输入一个目录路径');
            return;
        }
        
        this.setButtonLoading(this.setIndexDirectoryBtn, true, '设置中...');
        
        try {
            const response = await window.apiClient.setIndexDirectories(indexDirectories);
            
            if (response.success) {
                // 保存索引目录到本地存储
                this.saveIndexDirectories(indexDirectories);
                this.showAlert('索引目录设置成功');
                
                // 更新系统设置中的当前索引目录显示，使用换行符分隔而不是逗号
                this.updateCurrentIndexDirectory(indexDirectories.join('\n'));
            } else {
                this.showAlert(`设置失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error setting index directories:', error);
            this.showAlert('设置失败，请检查服务器连接');
        } finally {
            this.setButtonLoading(this.setIndexDirectoryBtn, false, '设置索引目录');
        }
    }

    async clearAllIndex() {
        if (!confirm('确定要清除所有索引分块吗？此操作不可恢复，需要重新索引所有文件。')) {
            return;
        }
        
        this.setButtonLoading(this.clearAllIndexBtn, true, '清除中...');
        
        try {
            const response = await window.apiClient.clearAllIndex();
            
            if (response.success) {
                this.showAlert('所有索引分块已清除');
                this.showSettingsOperationResult('清除所有索引分块', '成功清除所有索引分块', true);
                
                // 刷新系统状态
                if (window.indexManager) {
                    window.indexManager.loadSystemStatus();
                }
            } else {
                this.showAlert(`清除失败: ${response.message}`);
                this.showSettingsOperationResult('清除所有索引分块', `清除失败: ${response.message}`, false);
            }
        } catch (error) {
            console.error('Error clearing all index:', error);
            this.showAlert('清除失败，请检查服务器连接');
            this.showSettingsOperationResult('清除所有索引分块', '清除失败，请检查服务器连接', false);
        } finally {
            this.setButtonLoading(this.clearAllIndexBtn, false, '清除所有索引分块');
        }
    }

    async clearDirectoryIndex() {
        const indexDirectories = this.getIndexDirectories();
        
        if (indexDirectories.length === 0) {
            this.showAlert('请先设置索引目录');
            return;
        }
        
        if (!confirm(`确定要清除以下目录的索引分块吗？\n${indexDirectories.join('\n')}\n\n此操作不可恢复，需要重新索引这些目录中的文件。`)) {
            return;
        }
        
        this.setButtonLoading(this.clearDirectoryIndexBtn, true, '清除中...');
        
        try {
            const response = await window.apiClient.clearDirectoryIndex(indexDirectories);
            
            if (response.success) {
                this.showAlert('索引目录分块已清除');
                this.showSettingsOperationResult('清除索引目录分块', '成功清除指定目录的索引分块', true);
                
                // 刷新系统状态
                if (window.indexManager) {
                    window.indexManager.loadSystemStatus();
                }
            } else {
                this.showAlert(`清除失败: ${response.message}`);
                this.showSettingsOperationResult('清除索引目录分块', `清除失败: ${response.message}`, false);
            }
        } catch (error) {
            console.error('Error clearing directory index:', error);
            this.showAlert('清除失败，请检查服务器连接');
            this.showSettingsOperationResult('清除索引目录分块', '清除失败，请检查服务器连接', false);
        } finally {
            this.setButtonLoading(this.clearDirectoryIndexBtn, false, '清除索引目录分块');
        }
    }

    async refreshSystemInfo() {
        try {
            const response = await window.apiClient.getSystemStatus();
            
            if (response.success) {
                this.updateSystemStatusDisplay(response.data);
            }
        } catch (error) {
            console.error('Error refreshing system info:', error);
            this.updateSystemStatusDisplay(null, true);
        }
    }

    // 加载配置
    async loadConfig() {
        try {
            console.log('Loading configuration...');
            const response = await window.apiClient.get('/api/v1/config');
            console.log('Config response:', response);
            
            if (response && response.success) {
                const config = response.data;
                console.log('Config data:', config);
                
                // 填充MCP服务器配置
                const mcpApiKeyElement = document.getElementById('mcpApiKey');
                const mcpPortElement = document.getElementById('mcpPort');
                if (mcpApiKeyElement) mcpApiKeyElement.value = config.mcp?.api_key || '';
                if (mcpPortElement) mcpPortElement.value = config.mcp?.port || '';
                
                // 填充Web管理端配置
                const webPortElement = document.getElementById('webPort');
                if (webPortElement) webPortElement.value = config.server?.port || '';
                
                // 填充嵌入向量模型配置
                const bgeApiKeyElement = document.getElementById('bgeApiKey');
                const bgeHostElement = document.getElementById('bgeHost');
                const bgePortElement = document.getElementById('bgePort');
                if (bgeApiKeyElement) bgeApiKeyElement.value = config.bge_service?.api_key || '';
                if (bgeHostElement) bgeHostElement.value = config.bge_service?.host || '';
                if (bgePortElement) bgePortElement.value = config.bge_service?.port || '';
                
                // 填充向量数据库配置
                const vectorHostElement = document.getElementById('vectorHost');
                const vectorPortElement = document.getElementById('vectorPort');
                const vectorGrpcPortElement = document.getElementById('vectorGrpcPort');
                const vectorApiKeyElement = document.getElementById('vectorApiKey');
                if (vectorHostElement) vectorHostElement.value = config.vector_db?.host || '';
                if (vectorPortElement) vectorPortElement.value = config.vector_db?.port || '';
                if (vectorGrpcPortElement) vectorGrpcPortElement.value = config.vector_db?.grpc_port || '';
                if (vectorApiKeyElement) vectorApiKeyElement.value = config.vector_db?.api_key || '';
                
                // 填充索引文件配置
                const indexDirectoriesElement = document.getElementById('indexDirectories');
                if (indexDirectoriesElement && config.file_index?.index_directories) {
                    indexDirectoriesElement.value = config.file_index.index_directories.join('\n');
                }
                
                console.log('Configuration loaded successfully');
            } else {
                console.error('Failed to load config:', response?.message || 'Unknown error');
                this.showAlert('加载配置失败: ' + (response?.message || '未知错误'));
            }
        } catch (error) {
            console.error('Failed to load config:', error);
            this.showAlert('加载配置失败: ' + error.message);
        }
    }

    // 保存配置
    async saveConfig() {
        console.log('Saving configuration...');
        const saveButton = document.getElementById('saveConfigBtn');
        if (!saveButton) {
            console.error('Save config button not found');
            return;
        }
        
        this.setButtonLoading(saveButton, true, '保存中...');
        
        try {
            // 收集配置数据
            const mcpApiKeyElement = document.getElementById('mcpApiKey');
            const mcpPortElement = document.getElementById('mcpPort');
            const webPortElement = document.getElementById('webPort');
            const bgeApiKeyElement = document.getElementById('bgeApiKey');
            const bgeHostElement = document.getElementById('bgeHost');
            const bgePortElement = document.getElementById('bgePort');
            const vectorHostElement = document.getElementById('vectorHost');
            const vectorPortElement = document.getElementById('vectorPort');
            const vectorGrpcPortElement = document.getElementById('vectorGrpcPort');
            const vectorApiKeyElement = document.getElementById('vectorApiKey');
            const indexDirectoriesElement = document.getElementById('indexDirectories');
            
            const config = {
                mcp: {
                    api_key: mcpApiKeyElement ? mcpApiKeyElement.value : '',
                    port: mcpPortElement ? parseInt(mcpPortElement.value) || 8081 : 8081
                },
                server: {
                    port: webPortElement ? parseInt(webPortElement.value) || 8080 : 8080
                },
                bge_service: {
                    api_key: bgeApiKeyElement ? bgeApiKeyElement.value : '',
                    host: bgeHostElement ? bgeHostElement.value || 'localhost' : 'localhost',
                    port: bgePortElement ? parseInt(bgePortElement.value) || 8000 : 8000
                },
                vector_db: {
                    host: vectorHostElement ? vectorHostElement.value || 'localhost' : 'localhost',
                    port: vectorPortElement ? parseInt(vectorPortElement.value) || 6333 : 6333,
                    grpc_port: vectorGrpcPortElement ? parseInt(vectorGrpcPortElement.value) || 6334 : 6334,
                    api_key: vectorApiKeyElement ? vectorApiKeyElement.value : ''
                },
                file_index: {
                    index_directories: indexDirectoriesElement ? indexDirectoriesElement.value
                        .split('\n')
                        .map(dir => dir.trim())
                        .filter(dir => dir.length > 0) : []
                }
            };
            
            console.log('Config data to save:', config);
            
            const response = await window.apiClient.post('/api/v1/config', config);
            console.log('Save config response:', response);
            
            if (response && response.success) {
                this.showAlert('配置保存成功，重启服务器后生效');
                this.showSettingsOperationResult('保存配置', '配置保存成功，重启服务器后生效', true);
            } else {
                console.error('Failed to save config:', response?.message || 'Unknown error');
                this.showAlert('配置保存失败: ' + (response?.message || '未知错误'));
                this.showSettingsOperationResult('保存配置', '配置保存失败: ' + (response?.message || '未知错误'), false);
            }
        } catch (error) {
            console.error('Failed to save config:', error);
            this.showAlert('配置保存失败: ' + error.message);
            this.showSettingsOperationResult('保存配置', '配置保存失败: ' + error.message, false);
        } finally {
            this.setButtonLoading(saveButton, false, '保存配置');
        }
    }

    updateSystemStatusDisplay(data, isError = false) {
        const elements = {
            serverStatus: document.getElementById('serverStatus'),
            qdrantStatus: document.getElementById('qdrantStatus'),
            systemUptime: document.getElementById('systemUptime')
        };

        if (isError) {
            if (elements.serverStatus) {
                elements.serverStatus.textContent = '连接失败';
                elements.serverStatus.className = 'text-red-600 font-medium';
            }
            return;
        }

        if (elements.serverStatus) {
            elements.serverStatus.textContent = '运行中';
            elements.serverStatus.className = 'text-green-600 font-medium';
        }

        if (elements.qdrantStatus && data) {
            elements.qdrantStatus.textContent = data.qdrant_status === 'connected' ? '已连接' : '未连接';
            elements.qdrantStatus.className = data.qdrant_status === 'connected' ? 'text-green-600 font-medium' : 'text-red-600 font-medium';
        }

        if (elements.systemUptime && data && data.uptime) {
            // 假设data.uptime是ISO格式的日期字符串，计算与当前时间的差值
            const uptimeDate = new Date(data.uptime);
            const now = new Date();
            const uptimeSeconds = Math.floor((now - uptimeDate) / 1000);
            const uptimeText = this.formatUptime(uptimeSeconds);
            elements.systemUptime.textContent = uptimeText;
        }
    }

    formatUptime(uptime) {
        const days = Math.floor(uptime / (24 * 60 * 60));
        const hours = Math.floor((uptime % (24 * 60 * 60)) / (60 * 60));
        const minutes = Math.floor((uptime % (60 * 60)) / 60);
        
        let uptimeText = '';
        if (days > 0) uptimeText += `${days}天 `;
        if (hours > 0) uptimeText += `${hours}小时 `;
        uptimeText += `${minutes}分钟`;
        
        return uptimeText;
    }

    getIndexDirectories() {
        const indexDirectoriesElement = document.getElementById('indexDirectories');
        if (!indexDirectoriesElement) return [];
        
        return indexDirectoriesElement.value
            .split('\n')
            .map(dir => dir.trim())
            .filter(dir => dir.length > 0);
    }

    saveIndexDirectories(directories) {
        try {
            localStorage.setItem('indexDirectories', JSON.stringify(directories));
        } catch (error) {
            console.error('Error saving index directories:', error);
        }
    }

    loadSavedIndexDirectory() {
        try {
            const savedDirectories = localStorage.getItem('indexDirectories');
            if (savedDirectories) {
                const directories = JSON.parse(savedDirectories);
                const indexDirectoriesElement = document.getElementById('indexDirectories');
                if (indexDirectoriesElement) {
                    indexDirectoriesElement.value = directories.join('\n');
                }
                
                // 更新系统设置中的当前索引目录显示，使用换行符分隔而不是逗号
                this.updateCurrentIndexDirectory(directories.join('\n'));
            }
        } catch (error) {
            console.error('Error loading saved index directories:', error);
        }
    }

    updateCurrentIndexDirectory(directories) {
        const currentIndexDirectoryElement = document.getElementById('currentIndexDirectory');
        if (currentIndexDirectoryElement) {
            // 如果是多个目录，使用换行符分隔，避免在目录名称后添加多余逗号
            if (directories && directories.includes(',')) {
                currentIndexDirectoryElement.textContent = directories.replace(/, /g, '\n');
            } else {
                currentIndexDirectoryElement.textContent = directories || '-';
            }
        }
    }

    setButtonLoading(button, loading, loadingText = '处理中...') {
        if (!button) return;

        if (loading) {
            button.disabled = true;
            button.innerHTML = `<i class="fas fa-spinner fa-spin mr-2"></i>${loadingText}`;
        } else {
            button.disabled = false;
            // 恢复原始文本，这里需要根据具体按钮设置
            const originalTexts = {
                'setIndexDirectoryBtn': '设置索引目录',
                'clearAllIndexBtn': '清除所有索引分块',
                'clearDirectoryIndexBtn': '清除索引目录分块',
                'refreshSystemInfoBtn': '刷新系统信息',
                'saveConfigBtn': '保存配置'
            };
            const buttonId = button.id;
            button.innerHTML = originalTexts[buttonId] || '操作';
        }
    }

    showSettingsOperationResult(operation, message, success) {
        if (!this.settingsOperationResult || !this.settingsOperationContent) return;

        this.settingsOperationResult.classList.remove('hidden');
        
        const statusClass = success ? 'text-green-600' : 'text-red-600';
        const statusIcon = success ? 'fa-check-circle' : 'fa-exclamation-circle';
        
        this.settingsOperationContent.innerHTML = `
            <div class="flex items-center">
                <i class="fas ${statusIcon} ${statusClass} mr-2"></i>
                <span class="font-medium">${operation}:</span>
                <span class="ml-2">${message}</span>
            </div>
        `;
        
        // 5秒后自动隐藏
        setTimeout(() => {
            this.settingsOperationResult.classList.add('hidden');
        }, 5000);
    }

    showAlert(message) {
        alert(message);
    }
}

// 创建全局系统管理器实例
window.systemManager = new SystemManager();